﻿using System;
using System.Collections;
using System.Data;
using System.Globalization;
using System.IO;
using System.Windows.Forms;
using SQLDiagConfiguration.Properties;

namespace SQLDiagConfiguration
{
    public partial class ProfilerOptionsPage : BasePage
    {
        #region Constructor
        public ProfilerOptionsPage(DiagInfoObject obj)
        {
            DiagInfo = obj;
            InitializeComponent();
        }
        #endregion Constructor

        #region Page specific override methods
        public override void LoadState()
        {
            PopulateTemplatesBasedOnVersion();
            base.LoadState();
            LoadProfilerEventTree();
            bool enable = chkEnableSQLTrace.Checked;
            txtProfilerMaxfileSize.Enabled = enable;
            cbProfilerInterval.Enabled = enable;
            txtProfilerFileCount.Enabled = enable;
            tvProfilerEvents.Enabled = enable;
            cbSQLTraceTemplates.Enabled = enable;
        }
        public override void SaveState()
        {
            base.SaveState();
            SaveProfilerEventTree();
        }
        public override void LoadControlText()
        {
            base.LoadControlText();
            chkEnableSQLTrace.Text = Resources.strchkEnableSQLTrace;
            lblSQLTraceMaxFileSize.Text = Resources.strlblSQLTraceMaxFileSize;
            lblSQLTraceMaxNumFiles.Text = Resources.strlblSQLTraceMaxNumFiles;
            lblSQLTracePollingInterval.Text = Resources.strlblSQLTracePollingInterval;
            lblSQLTraceTemplate.Text = Resources.strlblSQLTraceTemplate;
        }
        #endregion Page specific override methods

        #region Event Handlers
        private void tvProfilerEvents_AfterCheck(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Parent == null)
            { 
                foreach (TreeNode child in e.Node.Nodes)
                {
                    child.Checked = e.Node.Checked;
                }
            }
        }

        private void chkEnableSQLTrace_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox cb = (CheckBox)sender;
            txtProfilerMaxfileSize.Enabled = cb.Checked;
            cbProfilerInterval.Enabled = cb.Checked;
            txtProfilerFileCount.Enabled = cb.Checked;
            tvProfilerEvents.Enabled = cb.Checked;
            cbSQLTraceTemplates.Enabled = (cb.Checked && cbSQLTraceTemplates.Items.Count >0);
        }
        #endregion Event Handlers
        
        #region Helper Methods
        private void LoadProfilerEventTree()
        {
            tvProfilerEvents.ShowLines = true;
            tvProfilerEvents.CheckBoxes = true;
            tvProfilerEvents.ShowNodeToolTips = true;
            PopulateNodes(DiagInfo.SQLDiagConfigDataSet);
 
        }
        public void SaveProfilerEventTree()
        {
            foreach (TreeNode tn in tvProfilerEvents.Nodes)
            {
                foreach (TreeNode t2 in tn.Nodes)
                {
                    int rowNumber = Convert.ToInt32(t2.Tag, CultureInfo.CurrentCulture);
                    DiagInfo.SQLDiagConfigDataSet.Tables[Resources.strEvent].Rows[rowNumber][Resources.strEnabled] = t2.Checked ? Resources.strTrue : Resources.strFalse;
                }
            }
        }
        public void PopulateTemplatesBasedOnVersion()
        {
            try
            {
                cbSQLTraceTemplates.Items.Clear();
                string dir = Resources.strBaseProfilerTemplatePath;
                string templateDir = (DiagInfo.Version.Length == 1)?DiagInfo.Version:DiagInfo.Version.Substring(0, 2);
                foreach (string fileName in Directory.EnumerateFileSystemEntries(dir + templateDir, Resources.strXMLExtention, SearchOption.TopDirectoryOnly))
                {
                    int index = fileName.LastIndexOf(Resources.strBackSlash, StringComparison.CurrentCulture);
                    string file = fileName.Substring(index+1);
                    TemplateComboBoxInfoObject tio = new TemplateComboBoxInfoObject(file, fileName);
                    cbSQLTraceTemplates.Items.Add(tio);
                }
                if (cbSQLTraceTemplates.Items.Count == 0)
                {
                    cbSQLTraceTemplates.Enabled = false;
                }
            }
            catch (UnauthorizedAccessException UAEx)
            {
                Console.WriteLine(UAEx.Message);
            }
            catch (PathTooLongException PathEx)
            {
                Console.WriteLine(PathEx.Message);
            }
            cbSQLTraceTemplates.DisplayMember = Resources.strFileName;
            cbSQLTraceTemplates.ValueMember = Resources.strFullName;
        }
        #endregion Helper Methods

        private void cbSQLTraceTemplates_SelectedIndexChanged(object sender, EventArgs e)
        {
            tvProfilerEvents.Nodes.Clear();
            DiagInfo.ProfilerEvents.Clear();
            if (cbSQLTraceTemplates.SelectedItem != null)
            {
                TemplateComboBoxInfoObject o = cbSQLTraceTemplates.SelectedItem as TemplateComboBoxInfoObject;
                DataSet tempDataSet = new DataSet();
                tempDataSet.ReadXml(o.FullName);
                tempDataSet.DataSetName = "Replace";
                tempDataSet.Locale = CultureInfo.CurrentCulture;
                PopulateNodes(tempDataSet);
                tempDataSet.Dispose();
            }
                                    
        }
        private void PopulateNodes(DataSet ds)
        {
            tvProfilerEvents.Nodes.Clear();
            DiagInfo.ProfilerEvents.Clear();
            int rowNumber = 0;
            int eventClassID = 0;
            DataTable evnts = ds.Tables[Resources.strEventType];
            DataRelation dr =ds.Relations[Resources.strEventRelation];
            if (ds.DataSetName == "Replace")
            {
                UpdateNodes(ds, Resources.strEventType, Resources.strEvent, Resources.strEventRelation,Resources.strEventTypeID);
            }
            foreach(DataRow r in evnts.Rows)
            {
                string className = r[Resources.strName].ToString();
                bool hasEnabledAtTypeLevel = false;
                ProfilerEventTypeObject eto = new ProfilerEventTypeObject(className, hasEnabledAtTypeLevel);
                DiagInfo.ProfilerEvents.Add(className, eto);
                eto.EventClassID = eventClassID;
                foreach(DataRow childRow in r.GetChildRows(dr))
                {
                    ProfilerEventInfoObject p = new ProfilerEventInfoObject();
                    p.ParentObj = eto;
                    p.Name = childRow[Resources.strName].ToString();
                    p.RowNumber = rowNumber;
                    p.Description = childRow[Resources.strDescription].ToString();
                    p.Enabled = Convert.ToBoolean(childRow[Resources.strEnabled],CultureInfo.CurrentCulture);
                    p.EventID = Convert.ToInt32(childRow[Resources.strEventId], CultureInfo.CurrentCulture);
                    rowNumber++;
                    eto.Children.Add(p.Name, p);
                }
            }
            foreach (DictionaryEntry evt in DiagInfo.ProfilerEvents)
            {
                ProfilerEventTypeObject parent = evt.Value as ProfilerEventTypeObject;
                TreeNode eventType = tvProfilerEvents.Nodes.Add(parent.EventTypeName);
                eventType.Tag = parent.HasEnabledAtClassLevel;
                int checkedEvents = 0;
                foreach (DictionaryEntry c in parent.Children)
                {
                    ProfilerEventInfoObject child = c.Value as ProfilerEventInfoObject;
                    TreeNode t = eventType.Nodes.Add(child.Name);
                    t.Tag = child.RowNumber;
                    t.ToolTipText = child.Description;
                    t.Checked = child.Enabled;
                    if(t.Checked == true)
                    {
                        checkedEvents++;
                    }
                }
                if (checkedEvents == parent.Children.Count)
                {
                    eventType.Checked = true;
                }
            }
        }

        // Delay the wiring up of the combobox selection change to avoid multiple reloading of the tree
        private void ProfilerOptionsPage_Load(object sender, EventArgs e)
        {
            this.cbSQLTraceTemplates.SelectedIndexChanged += new System.EventHandler(this.cbSQLTraceTemplates_SelectedIndexChanged);
        }

    }
}
